﻿using fuzhu;
using LH.Model.PU;
using LH.Model.SA;
using LH.Model.ST;
using LH.Models.APAR;
using LH.U8API.Bus; 
using LKU8.shoukuan;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using MySqlConnector;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSuarEntity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.Eventing.Reader;
using System.DirectoryServices.ActiveDirectory;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Reflection.Metadata;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Xml.Linq;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using XXX.Models.GL;
using XXX.Models.WDFT;
using XXX.Models.XXXEntities;
using ZDEntity;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;


namespace Yonyou.U8.BO
{
    //发货单
    public class DispatchlistVM : SA_DispatchList
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public DispatchlistVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       
        public  RetModel2 AddVerify()
        {
            try
            {

                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject($"当前单据号{this.head.cdlcode}已存在");
                }
                foreach (Body body in bodies)
                {
                    body.editprop = "A";
                }

                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }

                
                if (!DispatchlistCO.AddVerifySA_DispatchList(this, this.xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    //审核生成的销售出库单

                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    })
                         )
                    {
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                        db.Updateable<DispatchList>()
                            .SetColumns(x=>new DispatchList()
                            { dverifydate = dDate, cVerifier = head.cmaker })
                            .Where(u => u.DLID == iid).ExecuteCommand();

                        //查询销售出库单
                        var rd32id = db.Queryable<rdrecord32>()
                            .Where(x => x.cBusCode == ccode && x.cSource == "发货单")
                            .Select(x => x.ID).First();
                        if (rd32id != null)
                        {
                           if ( Rdrecord32DALCO.VerifyRdrecord32(DbHelper.GetDbString(rd32id), this.xmlConfig, "verify", out string err2))
                            {
                                    db.Updateable<rdrecord32>()
                               .SetColumns(x => new rdrecord32()
                               { dVeriDate = dDate, cHandler = head.cmaker,cMaker = head.cmaker })
                               .Where(u => u.ID == rd32id).ExecuteCommand();
                            }
                        }
                    }
                        
                }
                //else
                //{

                //    if (!SO_SOCO.OperateSaleOrder(id, "verify", out err))
                //    {
                //        //审核失败，需要删除数据
                //        SO_SOCO.OperateSaleOrder(id, "delete", out _);
                //        return DBService.ReErrObject("审核失败：" + err); ;
                //    }
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        /// <summary>
        /// 销售订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject($"当前单据号{this.head.cdlcode}不存在");
                }
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                })
                        )
                {
                    //查询销售出库单
                    var rd32id = db.Queryable<rdrecord32>()
                    .Where(x => x.cBusCode == head.cdlcode && x.cSource == "发货单" && SqlFunc.IsNull(x.cHandler,"")!="")
                    .Select(x => x.ID).First();
                    if (rd32id != null)
                    {
                        if (!Rdrecord32DALCO.VerifyRdrecord32(DbHelper.GetDbString(rd32id), this.xmlConfig, "unverify", out string err2))
                        {
                            return DBService.ReErrObject("销售出库单弃审失败：" + err2);
                        }
                    }
                }

                if (!DispatchlistCO.OperateSA_DispatchList(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }
                //else
                //{
                //    if (!SO_SOCO.OperateSaleOrder(ID, "delete", out err))
                //    {
                //        //删除失败,重新审核，保持原样
                //        SO_SOCO.OperateSaleOrder(ID, "verify", out _);
                //        return DBService.ReErrObject("删除失败：" + err);
                //    }
                return DBService.ReOKObject(head.csocode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        public RetModel2 Add_WanJi(WanJi_FaHuo_View_Lst obj)
        {
            var firstEntity = obj.vouList[0];
            //再次检查发货单是否存在
            if (ExistsByWanJiFaHuo(obj.vouList[0]))
            {
                return DBService.ReErrObject($"订单号{obj.vouList[0].cSoCode},日期{obj.vouList[0].dDate}的发货单已存在,不能重复导入;");
            }

            try
            {
                SA_DispatchList.Head head = new SA_DispatchList.Head
                {
                    cdlcode = "0000000002",//默认值
                    ddate = firstEntity.dDate.ToString("yyyy-MM-dd"),
                    //ccuscode = obj.cCusCode, //根据销售订单号读取
                    cmaker = obj.cMaker,
                    //cmemo = obj.cMemo,
                    cstcode = "01",
                    cbustype = "普通销售",
                    ivtid = "71",
                    bfirst = "0",
                    sbvid = "0",
                    isale = "0",
                    billafterlosssettle = "0",
                    bcusinvlimited = "0",
                    bbillbluesalelist = "0",
                    bbillredsalelist = "0",
                    bcredit = "否",
                    bcreditdate = "0",
                    bmustbook = "0",
                    breturnflag = "0",
                    cvouchtype = "05",
                    csocode = firstEntity.cSoCode
                    //cebexpresscode = obj.cEBExpressCode,
                    //cdefine1 = obj.cDefine1,
                    //cdefine2 = obj.cDefine2,
                    //cdefine3 = obj.cDefine3,
                    //cdefine4 = obj.cDefine4,
                    //cdefine5 = obj.cDefine5,
                    //cdefine6 = obj.cDefine6,
                    //cdefine7 = obj.cDefine7,
                    //cdefine8 = obj.cDefine8,
                    //cdefine9 = obj.cDefine9,
                    //cdefine10 = obj.cDefine10,
                    //cdefine11 = obj.cDefine11,
                    //cdefine12 = obj.cDefine12,
                    //cdefine13 = obj.cDefine13,
                    //cdefine14 = obj.cDefine14,
                    //cdefine15 = obj.cDefine15,
                    //cdefine16 = obj.cDefine16,

                };


                List<SA_DispatchList.Body> bodies = new List<SA_DispatchList.Body>();
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    if (obj.vouList != null && obj.vouList.Count > 0)
                    {
                        int i = 0;
                        foreach (var item in obj.vouList)
                        {
                            if (string.IsNullOrEmpty(item.cInvCode))
                            {
                                throw new Exception("存货编码不能为空");
                            }
                            if (item.iFHQty == 0)
                            {
                                throw new Exception("数量不能为0");
                            }
                            //读取销售订单的信息
                            int iSourceid = DbHelper.GetDbInt(item.iSosid);
                            WMS_GetSource source = db.Queryable<SO_SODetails>()
                            .InnerJoin<SO_SOMain>((a, b) => a.ID == b.ID && a.iSOsID == iSourceid)

                            .Select((a, b) => new WMS_GetSource
                            {
                                cSOCode = b.cSOCode,
                                cPTCode = b.cSTCode,
                                cCusCode = b.cCusCode,
                                cDefine1 = b.cCusName,
                                cexch_name = b.cexch_name,
                                iExchRate = b.iExchRate,
                                cDepCode = b.cDepCode,
                                cPersonCode = b.cPersonCode,
                                cBusType = b.cBusType,
                                iTaxRate = (decimal?)b.iTaxRate,
                                cbMemo = b.cMemo,
                                bsaleprice = a.bsaleprice,
                                iOriCost = a.iUnitPrice,
                                iOriTaxCost = a.iTaxUnitPrice,
                                iOriMoney = a.iMoney,
                                iOriTaxPrice = a.iTax,
                                iOriSum = a.iSum,
                                iSum = a.iNatSum,
                                iMoney = a.iNatMoney,
                                iTax = a.iNatTax,
                                iCost = a.iNatUnitPrice,
                                iSosid = a.iSOsID,
                                cItem_class = a.cItem_class,
                                cItemCode = a.cItemCode,
                                cItemName = a.cItemName,
                                cordercode = b.cSOCode,
                                isorowno = a.iRowNo


                            }).First();
                            if (source == null)
                            {
                              throw new Exception($"无法读取销售订单信息{item.cSoCode}");
                               
                            }
                            if (i == 0 && source != null)
                            {
                                head.cstcode = source.cPTCode;
                                head.cdepcode = source.cDepCode;
                                head.cpersoncode = source.cPersonCode;
                                head.cbustype = source.cBusType;
                                head.ccuscode = source.cCusCode;
                                head.ccusname = source.cDefine1;
                                head.csocode = source.cSOCode;
                                head.cinvoicecusname = source.cDefine1;
                                head.cinvoicecompany = source.cCusCode;
                                head.ccreditcuscode = source.cCusCode;
                                head.cexch_name = source.cexch_name;
                                head.iexchrate = DbHelper.GetDbString(source.iExchRate);
                                head.itaxrate = DbHelper.GetDbString(source.iTaxRate);
                                //根据客户具体设置
                                head.bsaleoutcreatebill = "0";
                            }
                           
                                //生成订单，读取仓库信息
                                WMS_GetSource source2 = db.Queryable<mom_orderdetail>()
                                .InnerJoin<mom_order>((a, b) => a.MoId == b.MoId && b.MoCode == item.cMoCode && a.InvCode == item.cInvCode)
                                .Select((a, b) => new WMS_GetSource
                                {
                                    cWhCode = a.WhCode,

                                }).First();

                            if (source2 == null)
                            {
                                throw new Exception($"无法读取对应生产订单信息{item.cMoCode}");
                            }
                            //                            select iorderdid, iordertype, iordercode, iorderseq, isodid, isotype, csocode, isoseq from rdrecords10

                            //select OrderType,OrderDId,OrderCode,OrderSeq from mom_orderdetail



                            i++;
                            SA_DispatchList.Body body = new SA_DispatchList.Body
                            {
                                cwhcode = source2.cWhCode,
                                cinvcode = item.cInvCode,
                                cgroupcode ="01",
                                 
                                //cfree1 = item.cFree1,
                                //cfree2 = item.cFree2,
                                //cfree3 = item.cFree3,
                                //cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iFHQty),
                                //cmemo = item.cBMemo,
                                //cbatch = item.cBatch,
                                csocode = item.cSoCode,
                                isosid = DbHelper.GetDbString(item.iSosid),

                                //生产订单号 表体10
                                cdefine31 = item.cMoCode,
                                //cdefine32 = item.cSoureRowId,

                                ////发货单货位，表体自定义项2
                                //cdefine23 = item.cPosCode,
                                ////从22 写到37
                                //cdefine22 = item.cDefine22,

                                //cdefine24 = item.cDefine24,
                                //cdefine25 = item.cDefine25,
                                //批量 表体5
                                cdefine26 = DbHelper.GetDbString(item.iMoQty),
                                //累计发货量，表体6
                                cdefine27 = DbHelper.GetDbString(item.iYFHQty),
                                //cdefine28 = item.cDefine28,
                                //cdefine29 = item.cDefine29,
                                //cdefine30 = item.cDefine30,
                                //cdefine33 = item.cDefine31,

                                //工单剩余数量 表体13
                                cdefine34 = DbHelper.GetDbString(item.iWFHQty),
                                //cdefine35 = item.cDefine35,

                                //cdefine36 = item.cDefine36,
                                //cdefine37 = item.cDefine37
                            };


                            //body.cunitid = source.cUnitID;
                            //body.iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                            body.itaxrate = DbHelper.GetDbString(source.iTaxRate);
                            body.irowno = (i + 1).ToString();

                            body.cordercode = source.cordercode;
                            body.iorderrowno = DbHelper.GetDbString(source.isorowno);
                            body.idiscount = "0";
                            body.kl = "100";
                            body.kl2 = "100";
                            if (source.bsaleprice == true)
                            {
                                body.bsaleprice = "1";
                            }
                            else
                            {
                                body.bsaleprice = "0";
                            }

                            body.bgift = "0";
                            //如果发货数量= 销售订单数量，直接取销售订单的单价和金额
                            if (DbHelper.GetDbdecimal(body.iquantity) == source.iQuantity)
                            {
                                body.inum = DbHelper.GetDbString(source.iNum);
                                body.itaxunitprice = DbHelper.GetDbString(source.iOriTaxCost);
                                body.iunitprice = DbHelper.GetDbString(source.iOriCost);
                                body.imoney = DbHelper.GetDbString(source.iOriMoney);
                                body.isum = DbHelper.GetDbString(source.iOriSum);
                                body.itax = DbHelper.GetDbString(source.iOriTaxPrice);
                                body.inatunitprice = DbHelper.GetDbString(source.iOriTaxPrice);
                                body.inatmoney = DbHelper.GetDbString(source.iCost);
                                body.inattax = DbHelper.GetDbString(source.iTax);
                                body.inatsum = DbHelper.GetDbString(source.iSum);
                            }
                            else
                            {
                                #region 处理金额： 根据含税单价反算单价和无税单价
                                body.itaxunitprice = DbHelper.GetDbString(source.iOriTaxCost);
                                decimal dOriSum = Math.Round(DbHelper.GetDbdecimal(body.iquantity) * DbHelper.GetDbdecimal(source.iOriTaxCost), 2);  //原币含税金额
                                body.iquotedprice = body.itaxunitprice;
                                decimal dOriMoney = Math.Round(DbHelper.GetDbdecimal((dOriSum / (1 + DbHelper.GetDbdecimal(body.itaxrate) / 100))), 2);  //不含税金额
                                decimal dOriTax = dOriSum - dOriMoney;  //原币税额
                                body.isum = DbHelper.GetDbString(dOriSum);
                                body.imoney = DbHelper.GetDbString(dOriMoney);
                                body.itax = DbHelper.GetDbString(dOriTax);
                                body.iunitprice = DbHelper.GetDbString(dOriMoney / DbHelper.GetDbdecimal(body.iquantity));
                                decimal dSum = dOriSum * DbHelper.GetDbdecimal(head.iexchrate);
                                decimal dMoney = dOriMoney * DbHelper.GetDbdecimal(head.iexchrate);
                                decimal dTax = dSum - dMoney;  //原币税额 
                                body.inatsum = DbHelper.GetDbString(dSum);
                                body.inatmoney = DbHelper.GetDbString(dMoney);
                                body.inattax = DbHelper.GetDbString(dTax);
                                body.inatunitprice = DbHelper.GetDbString(dMoney / DbHelper.GetDbdecimal(body.iquantity));

                                #endregion

                                bodies.Add(body);
                            }
                        }
                    }
                }
               
                head.csocode = bodies[0].csocode;
                this.head = head;
                this.bodies = bodies;

                if (!DispatchlistCO.AddVerifySA_DispatchList(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    //更改审核人
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        string sql = $"UPDATE dispatchlist SET cVerifier = CMAKER WHERE  cVerifier='{CanShu.cUserid}'   and cmaker<>'{CanShu.cUserid}'  ";
                        db.Ado.ExecuteCommand(sql);
                        //销售出库单制单人
                        sql = $"update rdrecord32 set cmaker = '{this.head.cmaker}' where cmaker='{CanShu.cUserid}'   and cdlcode='{id}'  ";
 db.Ado.ExecuteCommand(sql);

                    }

                }



                    //生成的id赋值
                    //head = id;
                    return DBService.ReOKObject(ccode);




            }
            catch (Exception ex)
            {

                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 发货单 变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 Change()
        {
            try
            {
                string idcheck = "";
                if (!Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前单据号不存在");
                }

                head.dlid = idcheck;
                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }
                head.editprop = "M";
                //增加变更人
                //head.cchanger = head.cmaker;
                //head.dmoddate = head.ddate;


                //变更的处理， （1） 主键id，子表isosid写入（2）判断是新增，还是修改，还是删除 （3）时间戳读取


                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //取表头的时间戳
                    string sql = string.Format("select  cmaker,cverifier, convert(char,convert(money,ufts),2) ufts from dispatchlist where cdlCode = '{0}' ", head.cdlcode);
                    Head u8head = db.Ado.SqlQuery<Head>(sql).FirstOrDefault();

                    head.ufts = u8head.ufts;
                    //修改人更改
                    head.cchanger = head.cmaker;
                    //head. = head.cverifier;
                    //head.cmodifydate = DateTime.Now.ToString("yyyy-MM-dd");
                    head.cmaker = u8head.cmaker;
                    head.cverifier = u8head.cverifier;
                    head.dlid = idcheck;
                    //默认审核状态,没有勇
                    //head.istatus = "1";
                    //取表体信息,默认全部是D，循环后，剩余是D的，再写入表体
                    sql = string.Format("select 'D' AS editprop,  autoid,cdefine33, convert(char,convert(money,dufts),2) dufts  from dispatchlists where dlid = '{0}' ", idcheck);

                    List<Body> u8bodies = db.Ado.SqlQuery<Body>(sql);
                    int bmodify = 0;//编辑标记
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        bodies[i].dlid = idcheck;
                        bmodify = 0;
                        for (int j = 0; j < u8bodies.Count; j++)
                        {
                            if (bodies[i].cdefine33 == u8bodies[j].cdefine33)
                            {
                                //表体不需要时间戳
                                //bodies[i].dufts = u8bodies[j].dufts;
                                bodies[i].autoid = u8bodies[j].autoid;
                                bodies[i].editprop = "M";
                                u8bodies[j].editprop = "M";
                                bmodify = 1;
                                continue;
                            }
                        }
                        if (bmodify == 0)
                        {
                            bodies[i].editprop = "A";
                        }

                    }
                    //循环后检查删除的
                    for (int j = 0; j < u8bodies.Count; j++)
                    {
                        if (u8bodies[j].editprop == "D")
                        {
                            Body body = new Body();
                            body.dlid = idcheck;
                            body.editprop = "D";
                            //body.dufts = u8bodies[j].dufts;
                            body.autoid = u8bodies[j].autoid;
                            bodies.Add(body);
                        }
                    }

                }

                string err = "";
                if (!DispatchlistCO.ChangeSA_DispatchList(this, xmlConfig, out err, out string id, out string ccode))
                {

                    return DBService.ReErrObject("变更失败：" + err);
                }

                return DBService.ReOKObject("变更完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 完善发货单信息,处理客户，金额，税率，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetAddInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                //取销售订单表头信息
                WMS_GetSource source = db.Queryable<SO_SOMain>()
                     .InnerJoin<SO_SODetails>((x, b) => x.ID == b.ID && b.cDefine33 == bodies[0].cdefine32)
                    .Select((x, b) => new WMS_GetSource
                    {
                        cSOCode = x.cSOCode,
                        cPTCode = x.cSTCode,
                        cCusCode = x.cCusCode,
                        cDefine1 = x.cCusName,
                        cexch_name = x.cexch_name,
                        iExchRate = x.iExchRate,
                        cDepCode = x.cDepCode,
                        cPersonCode = x.cPersonCode,
                        cBusType = x.cBusType,
                        iTaxRate = (decimal?)x.iTaxRate,
                    }).First();

                if (source != null)
                {
                    head.cstcode = source.cPTCode;
                    head.cdepcode = source.cDepCode;
                    head.cpersoncode = source.cPersonCode;
                    head.cbustype = source.cBusType;
                    head.ccuscode = source.cCusCode;
                    head.ccusname = source.cDefine1;
                    head.csocode = source.cSOCode;
                    head.cinvoicecusname = source.cDefine1;
                    head.cinvoicecompany = source.cCusCode;
                    head.ccreditcuscode = source.cCusCode;
                    head.cexch_name  = source.cexch_name;
                    head.iexchrate =DbHelper.GetDbString(source.iExchRate);
                    head.itaxrate = DbHelper.GetDbString( source.iTaxRate);
                    //根据客户具体设置
                    head.bsaleoutcreatebill = "0";

                }
                else
                {
                    return $"Error: 来源销售订单行id{bodies[0].cdefine32}查找不到销售订单号";
                }

                //取销售订单信息

                for (int i = 0; i < bodies.Count; i++)
                {
                    
                    WMS_GetSource sourcerow = db.Queryable<SO_SOMain>()
                               .InnerJoin<SO_SODetails>((a, b) => a.ID == b.ID  && b.cDefine33 == bodies[i].cdefine32)
                               .Select((a, b) => new WMS_GetSource
                               {  
                                   Autoid = b.iSOsID,
                                   cInvCode = b.cInvCode,
                                   cUnitID = b.cUnitID,
                                   iChangeRate = b.iInvExchRate,
                                   iQuantity = (decimal)b.iQuantity,
                                   iNum = b.iNum,
                                   cbMemo = b.cMemo,
                                   iTaxRate  = b.iTaxRate,
                                   bsaleprice = b.bsaleprice,
                                   iOriCost = b.iUnitPrice,
                                   iOriTaxCost = b.iTaxUnitPrice,
                                   iOriMoney = b.iMoney,
                                   iOriTaxPrice = b.iTax,
                                   iOriSum = b.iSum,
                                   iSum = b.iNatSum,
                                   iMoney = b.iNatMoney,
                                   iTax =b.iNatTax,
                                   iCost  = b.iNatUnitPrice, 
                                   iSosid = b.iSOsID, 
                                   cItem_class = b.cItem_class,
                                   cItemCode = b.cItemCode,
                                   cItemName = b.cItemName ,
                                   cordercode  = a.cSOCode,
                                   isorowno = b.iRowNo

                               }).First();
                    if (sourcerow == null)
                    {
                        return  $"来源订单行id{bodies[i].cdefine32}关联不到销售订单" ;
                    }
                    else
                    {
                        bodies[i].isosid = DbHelper.GetDbString(sourcerow.Autoid);
                        //bodies[i].cinvcode = sourcerow.cInvCode;
                        bodies[i].cunitid =  sourcerow.cUnitID;
                        bodies[i].iinvexchrate = DbHelper.GetDbString(sourcerow.iChangeRate);
                        bodies[i].itaxrate = DbHelper.GetDbString(sourcerow.iTaxRate);
                        bodies[i].irowno = (i + 1).ToString();
                        bodies[i].isosid = DbHelper.GetDbString(sourcerow.iSosid);
                        bodies[i].cordercode =  sourcerow.cordercode;
                        bodies[i].iorderrowno = DbHelper.GetDbString(sourcerow.isorowno);
                        bodies[i].idiscount = "0";
                        bodies[i].kl = "100";
                        bodies[i].kl2 = "100";
                        if (sourcerow.bsaleprice == true)
                        {
                            bodies[i].bsaleprice = "1";
                        }
                        else
                        {
                            bodies[i].bsaleprice = "0";
                        }

                        bodies[i].bgift = "0";
                        //如果发货数量= 销售订单数量，直接取销售订单的单价和金额
                        if (DbHelper.GetDbdecimal(bodies[i].iquantity) == sourcerow.iQuantity)
                        {
                            bodies[i].inum = DbHelper.GetDbString(sourcerow.iNum);
                            bodies[i].itaxunitprice = DbHelper.GetDbString(sourcerow.iOriTaxCost);
                            bodies[i].iunitprice = DbHelper.GetDbString(sourcerow.iOriCost);
                            bodies[i].imoney = DbHelper.GetDbString(sourcerow.iOriMoney);
                            bodies[i].isum = DbHelper.GetDbString(sourcerow.iOriSum);
                            bodies[i].itax = DbHelper.GetDbString(sourcerow.iOriTaxPrice);
                            bodies[i].inatunitprice= DbHelper.GetDbString(sourcerow.iOriTaxPrice);
                            bodies[i].inatmoney = DbHelper.GetDbString(sourcerow.iCost);
                            bodies[i].inattax = DbHelper.GetDbString(sourcerow.iTax);
                            bodies[i].inatsum = DbHelper.GetDbString(sourcerow.iSum);
                        }
                        else
                        {
                            #region 处理金额： 根据含税单价反算单价和无税单价
                            bodies[i].itaxunitprice = DbHelper.GetDbString(sourcerow.iOriTaxCost);
                            decimal dOriSum = Math.Round(DbHelper.GetDbdecimal(bodies[i].iquantity)* DbHelper.GetDbdecimal(sourcerow.iOriTaxCost),2);  //原币含税金额
                            bodies[i].iquotedprice = bodies[i].itaxunitprice;
                            decimal dOriMoney = Math.Round(DbHelper.GetDbdecimal((dOriSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100))),2);  //不含税金额
                            decimal dOriTax = dOriSum - dOriMoney;  //原币税额
                            bodies[i].isum = DbHelper.GetDbString(dOriSum);
                            bodies[i].imoney = DbHelper.GetDbString(dOriMoney);
                            bodies[i].itax = DbHelper.GetDbString(dOriTax);
                            bodies[i].iunitprice = DbHelper.GetDbString(dOriMoney / DbHelper.GetDbdecimal(bodies[i].iquantity));
                            decimal dSum = dOriSum * DbHelper.GetDbdecimal(head.iexchrate);
                            decimal dMoney = dOriMoney * DbHelper.GetDbdecimal(head.iexchrate);
                            decimal dTax = dSum - dMoney;  //原币税额 
                            bodies[i].inatsum = DbHelper.GetDbString(dSum);
                            bodies[i].inatmoney = DbHelper.GetDbString(dMoney);
                            bodies[i].inattax = DbHelper.GetDbString(dTax);
                            bodies[i].inatunitprice = DbHelper.GetDbString(dMoney / DbHelper.GetDbdecimal(bodies[i].iquantity)); 
                          
                            #endregion
                        }
                    }
                    InvProperty invProperty = new InventoryVM().GetInvProperty(bodies[i].cinvcode, "", "");
                    if (invProperty == null)
                    {
                        return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), bodies[i].cinvcode);
                    }
                    else
                    {
                        bodies[i].cgroupcode = invProperty.cGroupCode;
                        bodies[i].igrouptype = invProperty.iGroupType;
                    }
                    FitemVM fitemVM = new FitemVM();

                    if (fitemVM.GetName(bodies[i].citem_class, bodies[i].citemcode, out string citem_cname, out string citemname) == "ok")
                    {
                        bodies[i].citem_cname = citem_cname;
                        bodies[i].citemname = citemname;
                    }
                }
            }
            
            return "ok";
        }
        /// <summary>
        /// 传入json转换成PuAppVouchVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public DispatchlistVM GetAddEntity(API_Dispatchlist obj, ref string cErr)
        {

            try
            {


                if (string.IsNullOrWhiteSpace(obj.cDLCode))
                {
                    cErr = "单据号不能为空";
                    return null;
                }
                //cCode = obj.cDLCode;
                if (string.IsNullOrWhiteSpace(obj.cMaker))
                {
                    cErr = "制单人不能为空";
                    return null;
                }
                if (string.IsNullOrWhiteSpace(obj.cVerifier))
                {
                    cErr = "审核人不能为空";
                    return null;
                }


                SA_DispatchList.Head head = new SA_DispatchList.Head
                {
                    cdlcode = obj.cDLCode,
                    ddate = obj.dDate,
                    ccuscode = obj.cCusCode,
                    cmaker = obj.cMaker,
                    cmemo = obj.cMemo,
                    cstcode = "01",
                    cbustype = "分期收款",
                    ivtid = "71",
                    bfirst = "0",
                    sbvid = "0",
                    isale = "0",
                    billafterlosssettle = "0",
                    bcusinvlimited = "0",
                    bbillbluesalelist = "0",
                    bbillredsalelist = "0",
                    bcredit = "否",
                    bcreditdate = "0",
                    bmustbook = "0",
                    breturnflag = "0",
                    cvouchtype = "05",
                    cebexpresscode = obj.cEBExpressCode,
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,

                };


                List<SA_DispatchList.Body> bodies = new List<SA_DispatchList.Body>();
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    if (obj.itemList != null && obj.itemList.Count > 0)
                    {
                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(item.cInvCode))
                            {
                                cErr = "存货编码不能为空";
                                return null;
                            }
                            if (item.iQuantity == 0)
                            {
                                cErr = "数量不能为0";
                                return null;
                            }
                            i++;
                            SA_DispatchList.Body body = new SA_DispatchList.Body
                            {
                                cwhcode = item.cWhCode,
                                cinvcode = item.cInvCode,
                                cfree1 = item.cFree1,
                                cfree2 = item.cFree2,
                                cfree3 = item.cFree3,
                                cfree4 = item.cFree4,
                                irowno = item.iRowNo,
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                cmemo = item.cBMemo,
                                cbatch = item.cBatch,
                                csocode = item.cSoCode,
                                isum = DbHelper.GetDbString(item.iOriSum),
                                iquotedprice = DbHelper.GetDbString(item.iNatTaxUnitPrice),
                                itaxunitprice = DbHelper.GetDbString(item.iOriTaxUnitPrice),
                                iunitprice = DbHelper.GetDbString(item.iOriUnitPrice),
                                imoney = DbHelper.GetDbString(item.iOriMoney),
                                itax = DbHelper.GetDbString(item.iOriTax),
                                inatunitprice = DbHelper.GetDbString(item.iNatTaxUnitPrice),
                                inatmoney = Math.Round(DbHelper.GetDbdecimal(item.iOriMoney) * DbHelper.GetDbdecimal(head.iexchrate), 2).ToString(),
                                inattax = Math.Round(DbHelper.GetDbdecimal(item.iOriTax) * DbHelper.GetDbdecimal(head.iexchrate), 2).ToString(),
                                //inatdiscount = DbHelper.GetDbString(Math.Round(DbHelper.GetDbdecimal(item.idiscount) * DbHelper.GetDbdecimal(head.iexchrate), 2)).ToString(),
                                inatsum = Math.Round(DbHelper.GetDbdecimal(item.iOriSum) * DbHelper.GetDbdecimal(head.iexchrate), 2).ToString(),

                                //当前行id
                                cdefine31 = item.cRowId,
                                cdefine32= item.cSoureRowId,

                                //发货单货位，表体自定义项2
                                cdefine23 = item.cPosCode,
                                //从22 写到37
                                cdefine22 = item.cDefine22,
                               
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                cdefine33 = item.cDefine31,


                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37
                            };
                             
                        bodies.Add(body);
                    }
                }
            }
                    head.csocode = bodies[0].csocode;
                    DispatchlistVM model = new DispatchlistVM(head, bodies);



                    return model;

                }
                catch (Exception ex)
                {
                    cErr = ex.Message;
                    return null;
                }





            }

        /// <summary>
        /// 传入json转换成PuAppVouchVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public DispatchlistVM GetCodeEntity(API_Dispatchlist obj, ref string cErr)
        {

            try
            {

                SA_DispatchList.Head head = new SA_DispatchList.Head();
                head.cdlcode = obj.cDLCode;
                List<SA_DispatchList.Body> bodies = new List<SA_DispatchList.Body>();

                DispatchlistVM model = new DispatchlistVM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }
        /// <summary>
        /// <summary>
        /// 检查发货单号是否存在
        /// </summary>
        /// <param name="id">输出dlid</param>
        /// <returns></returns>
        public bool Exists(ref string idcheck)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
               DispatchList dl =db.Queryable<DispatchList>().Where(x => x.cDLCode == this.head.cdlcode).First();
                if (dl == null)
                {
                    idcheck = "";
                    return false; 
                }
                else
                {
                    idcheck = dl.DLID.ToString();
                    return true;
                } 
            } 
        
        }

        /// <summary>
        /// 检查产成品入库号是否存在，根据moCode和banCi
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ExistsByWanJiFaHuo(WanJi_FaHuo_View entity)
        {


            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                string sql = @"SELECT COUNT(*) FROM dispatchlist a  
WHERE a.dDate=@dDate and a.cSoCode=@cSoCode   ";
                int icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql, new
                {
                    dDate = entity.dDate,
                    cSoCode = entity.cSoCode, 
                }));


                if (icnt > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }


    }
}
